<template>
<label class="bh-checkbox-button"
	:class="[
		size ? 'bh-checkbox-button--' + size : '',
		{ 'is-disabled': isDisabled },
        { 'is-checked': isChecked },
	]">
	<input type="checkbox" class="bh-checkbox-button__original" @change="handleChange" v-model="model" />
	<span class="bh-checkbox-button__inner">
		<slot></slot>
	</span>
</label>
</template>

<script>
import Emitter from '../../../../src/mixins/emitter';

export default {
	name: 'bh-checkbox-button',
	componentName: 'BHCheckboxButton',
	mixins: [Emitter],
	props: {
		value: {},
		label: {},
		disabled: Boolean,
		checked: Boolean,
	},
	data() {
		return {
			selfModel: false,
		};
	},
	computed: {
		model: {
			get() {
				if(this._checkboxGroup) {
					return this._checkboxGroup.value;
					//return this._checkboxGroup.value.includes(this.label);
				}else if(this.value != undefined) {
					return this.value	
				}
				return this.selfModel;
			},
			set(val) {
				if(this._checkboxGroup) {
					this.$emit('input', val);
					//this.$dispatch('BHCheckboxGroup', 'handleCheckboxClick', [this.label, val]);
				}else if(this.value != undefined) {
					this.$emit('input', val);
				}else {
					this.selfModel = val;
				}
			},
		},
		// 分组
		_checkboxGroup() {
			let parent = this.$parent;
			if (parent.$options.componentName == 'BHCheckboxGroup') {
				return parent;
			}

			return false;
		},
		size() {
			return this._checkboxGroup.size;
		},
		isChecked() {
			if ({}.toString.call(this.model) === '[object Boolean]') {
				return this.model;
			}else if(Array.isArray(this.model)) {
				return this.model.indexOf(this.label) > -1;
			}else if(this.value != undefined) {
				return this.model == this.label;
			}

			return this.model;
		},
		isLimitDisabled() {
			const { max, min } = this._checkboxGroup;
			return !!(max || min) &&
				(this.model.length >= max && !this.isChecked) ||
				(this.model.length <= min && this.isChecked);
		},
		isDisabled() {
			return this._checkboxGroup && this._checkboxGroup.disabled || this.disabled || this.isLimitDisabled;
		},
	},
	methods: {
		handleChange(ev) {
			if(this.isDisabled) {
				return;
			}
			let value;
			if (ev.target.checked) {
				value = true;
			} else {
				value = false;
			}
			this.$emit('change', value, ev);
			this.$nextTick(() => {
				if(this._checkboxGroup) {
					this.handleCheckboxClick(ev);
				}else {
					this.$emit('change', this.model);
				}
			});
		},
		handleCheckboxClick(ev) {
			this.$dispatch('BHCheckboxGroup', 'handleCheckboxClick', [this.label, ev.target.checked]);
		},
	},
}
</script>
